package org.kaer.election.utils;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;

import com.google.gson.Gson;

import org.kaer.election.trade.ExampleClient;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Calendar;
import java.util.Hashtable;

public class UdpHelper {
    private static String mserviceIP = "255.255.255.255";
    //	private String mserviceIP = "192.168.40.207";
    // private String mserviceIP = "192.168.40.200";
    // private String mserviceIP = "172.20.125.174";
    private int mport = 6311;
    private int mwsport = 6310;
    // |KAER | 2字节length（整条消息长度,网络序) | VoteWriter|
    private String mhead = "KAER";
    // private String mhead = "vote";
    private String mcmd = "VoteWriter";
    private int mlen = 16;
    public Hashtable<String, ExampleClient> inetaddressstring6 = new Hashtable<String, ExampleClient>();
    static Gson gson = new Gson();
    private Context mcontext = null;
    // private Publicdata app = null;
    private UdpSearchResultInterface mUdpResultInterface;

    public UdpHelper(Context context, UdpSearchResultInterface muUdpSearchResultInterface) {
        mcontext = context;
        this.mUdpResultInterface = muUdpSearchResultInterface;
    }

    public void sendMsg() {
        //
        byte[] byte4 = new byte[2];
        byte4[0] = 0x00;
        byte4[1] = (byte) mlen;
        String strlen = new String(byte4);
        String msg = mhead + strlen + mcmd;
        if (NetworkUtil.isAvailable(mcontext)) {
            new UdpSendTask().execute(msg.getBytes());
        } else {
            Intent intent = new Intent();
            intent.putExtra("msg", "网络未连接");
            notifyUI(-1, intent);
        }
    }

    private void notifyUI(int code, Intent intent) {
        if (mUdpResultInterface != null) {
            mUdpResultInterface.searchResult(code, intent);
        }
    }

    private byte datareceive[] = new byte[1024];

    public void sendMsg(byte[] data) {
        try {

            DatagramSocket client = new DatagramSocket();

            InetAddress addr;
            // Log.i("UdpHelper", "MyApplication.serviceIP: " +
            // MyApplication.serviceIP);

            addr = InetAddress.getByName("255.255.255.255");

            int port = mport;
            DatagramPacket sendPacket = new DatagramPacket(data, data.length, addr, port);
            client.send(sendPacket);

            client.close();
        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * @param moduleName    recordphone
     * @param interfaceName
     * @param msg
     * @param code
     * @param success
     * @return
     */
    public static byte[] packMsg(String moduleName, String interfaceName, String msg, int code, int success) {
        byte[] module = moduleName.getBytes();
        byte[] ite = interfaceName.getBytes();
        byte[] data = msg.getBytes();

        Calendar mCalendar = Calendar.getInstance();
        int curTime = (int) (mCalendar.getTimeInMillis() / 1000);

        ByteBuffer buffer = ByteBuffer.allocate(1 + 1 + 4 + 1 + 4 + 2 + 4 + module.length + ite.length + data.length);
        try {
            buffer.put((byte) module.length);
            buffer.put((byte) ite.length);
            buffer.order(ByteOrder.BIG_ENDIAN);
            buffer.putInt(0);
            buffer.put((byte) success);
            buffer.putInt(code);
            buffer.putShort((short) msg.length());
            buffer.putInt(curTime);
            buffer.put(module);
            buffer.put(ite);
            buffer.put(data);

            // Log.i("UdpHelper",
            // "packMsg = " + ByteUtils.formatData(buffer.array())
            // + " buffer.remaining() = " + buffer.remaining());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer.array();

    }

    class UdpSendTask extends AsyncTask<byte[], Integer, Intent> {
        int retCode = -1;

        @Override
        protected Intent doInBackground(byte[]... params) {
            // TODO Auto-generated method stub
            Intent intent = new Intent();
            // if(false){
            try {
                DatagramSocket client = new DatagramSocket();
                InetAddress addr;
                addr = InetAddress.getByName(mserviceIP);
                int port = mport;
                DatagramPacket sendPacket = new DatagramPacket(params[0], params[0].length, addr, port);
                // sendPacket.setData(msg.getBytes());
                // sendPacket.setLength(msg.length());
                // sendPacket.setAddress(addr);
                client.setBroadcast(true);
                client.send(sendPacket);

                DatagramPacket receivePacket = new DatagramPacket(datareceive, datareceive.length);

                client.setSoTimeout(15000);

                client.receive(receivePacket);
                String str5 = new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength());
                InetAddress broadcastAddr = receivePacket.getAddress();
                String straddress = broadcastAddr.getHostName();
                String hostAddress = broadcastAddr.getHostAddress();
                LogUtils.i("hostAddress = " + hostAddress);

                intent.putExtra("msg", "IP" + hostAddress); //
                intent.putExtra("ip", hostAddress);
                retCode = 0;
                client.close();
            } catch (SocketException e) {
                // TODO Auto-generated catch block
                intent.putExtra("msg", "搜索失败，请重新尝试"); //

                e.printStackTrace();
            } catch (UnknownHostException e) {
                intent.putExtra("msg", "主机信息无法获取"); //

                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                intent.putExtra("msg", "没有搜索到可用服务"); //

                e.printStackTrace();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                intent.putExtra("msg", "搜索失败"); //
                e.printStackTrace();
            }

            return intent;
        }

        @Override
        protected void onPostExecute(Intent result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            notifyUI(retCode, result);

        }

    }

    public interface UdpSearchResultInterface {
        public void searchResult(int result, Intent intent);
    }
}
